package org.wicketstuff.viewstack.common;

import org.apache.wicket.MarkupContainer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.wicketstuff.viewstack.model.IViewStackModel;
import org.wicketstuff.viewstack.view.IView;

/**
 *
 * @author fernando wermus
 * @author dtoffe
 */
public class ViewStack extends Panel implements IViewStack
{
    
	private static final long serialVersionUID = -7710339146435944043L;
	protected static final String ACTIVE_VIEW = "activeView";

	protected ViewStack(String id){
		super(id);
	}
	/**
	 * 
	 * @param id
	 */
	public ViewStack(String id, IModel model)
	{
		super(id, model);
		setOutputMarkupId(true);
		//addOrReplace(new EmptyPanel(ACTIVE_VIEW));
	}

	/**
	 *
	 * @return
	 */
	public String getView()
	{
		if (getModelObject() == null) {
			return "No view selected";
		} else {
			IView viewItem=(IView) getModelObject();
			return viewItem.getTitle();
		}
	}

	/**
	 *
	 * @param viewItem
	 */
	public void setSelectedView(IView viewItem)
	{
		getContainer().replace(viewItem.getPanel(ACTIVE_VIEW));
	}

	@SuppressWarnings("unchecked")
	@Override protected void onBeforeRender() {
		IViewStackModel vs=(IViewStackModel) getModelObject();
		IView viewItem=(IView) vs.getActiveView();
		Panel panel=viewItem.getPanel(ACTIVE_VIEW);
		getContainer().addOrReplace(panel);
		super.onBeforeRender();
	}
	protected MarkupContainer getContainer() {
		return this;
	}
	public void refrescar(AjaxRequestTarget target) {
		target.addComponent(this);
	}

}
